package com.cn.yunhe;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


/**
 * http://127.0.0.1:8080/CsWeb002/service/user101
 * http://127.0.0.1:8080/CsWeb002/service/order101
 * 
 * @author ZSL
 *
 */
//@WebServlet("/service/*")
public class ServiceServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	private static Map<String,ActionMapper> actionMap = new HashMap<String,ActionMapper>();
      

	public void init(ServletConfig config) throws ServletException {
		
		ActionMapper user101 =  new ActionMapper();
		user101.setClassName("com.cn.yunhe.handle.UserHandler");
		user101.setMethodName("getUser");
		actionMap.put("/user101", user101);
		
		ActionMapper order101 =  new ActionMapper();
		order101.setClassName("com.cn.yunhe.handle.OrderHandler");
		order101.setMethodName("getOrder");
		actionMap.put("/order101", order101);
		
		
		
		
		
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String cs =request.getRequestURI();
		String path = request.getContextPath();
		path = cs.substring(path.length()+"service".length()+1);
		
		
		
		//ActionMapper actMap = actionMap.get(path);

		

		
		try {
			SAXReader reader = new SAXReader();
			String xmlpath = this.getClass().getResource("/yunhe.xml").getPath();		
			Document doc = reader.read(new File(xmlpath));
			Element node = (Element) doc.selectSingleNode("//actions//action[@url='"+path+"']");
			String classNameStr = node.attributeValue("class");
			String methodNameStr = node.attributeValue("method");
			
			
			
			
			Class className = Class.forName(classNameStr);
			Method methodName = className.getMethod(methodNameStr);
			String page = (String) methodName.invoke(className.newInstance());
			
			
			Element rsEle =(Element) node.selectSingleNode("//result[@name='"+page+"']");
			
			String returnPath = rsEle.getText();
			
			request.getRequestDispatcher(returnPath).forward(request, response);	
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
